package cn.duckerkj.base.aop;

import java.lang.reflect.Method;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import cn.duckerkj.base.datasource.DynmicDataSourceContextHolder;


@Aspect
@Order(-1)
@Component
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class DataSourceAspect {
	private Logger log = LoggerFactory.getLogger(DataSourceAspect.class);  
	  
    ThreadLocal<Long> startTime = new ThreadLocal<>();  
  
    
    @Pointcut("execution(* cn.duckerkj.service..*ServiceImpl.*(..))") 
    public void webLog(){}  
  
    @Before("webLog()")  
    public void doBefore(JoinPoint joinPoint) throws Throwable {  
        startTime.set(System.currentTimeMillis());  
        Method method = joinPoint.getTarget().getClass().getDeclaredMethod(joinPoint.getSignature().getName());
        log.info("切入点: " + joinPoint.getTarget().getClass().getName() + "类中"
				+ method.getName() + "方法");
        
        System.err.println("@@@@@@@@@"+DynmicDataSourceContextHolder.getDataSourceKey());
        DynmicDataSourceContextHolder.clear();
        System.err.println("#########"+DynmicDataSourceContextHolder.getDataSourceKey());
		if (joinPoint.getTarget().getClass().getName().contains("Test")) {
			if (method.getName().startsWith("add")
					|| method.getName().startsWith("create")
					|| method.getName().startsWith("save")
					|| method.getName().startsWith("edit")
					|| method.getName().startsWith("update")
					|| method.getName().startsWith("delete")
					|| method.getName().startsWith("remove")
					|| method.getName().startsWith("grant")
					|| method.getName().startsWith("get")
					) {
				log.info("切换到: primaryDataSource");
				DynmicDataSourceContextHolder.setDataSourceKey("primaryDataSource"); 
				return;
			} else {
				log.info("切换到: secondDataSource");
				DynmicDataSourceContextHolder.setDataSourceKey("secondDataSource");
				return;
			}
		}
  
    }  
  
    @AfterReturning(returning = "ret", pointcut = "webLog()")  
    public void doAfterReturning(Object ret) throws Throwable {  
        // 处理完请求，返回内容  
        log.info("RESPONSE=" + ret);  
        log.info("SPEND TIME=" + (System.currentTimeMillis() - startTime.get()));  
        DynmicDataSourceContextHolder.clear();
    }  
    // 抛出Exception之后被调用
    @AfterThrowing(throwing = "ex", pointcut = "webLog()") 
 	public void afterThrowing(Exception ex) throws Throwable {
 		//DataSourceSwitcher.setReadParkingData();
 		log.error("数据操作出现异常,切换到: readParkingData"+ex.getMessage());
 	}
}
